// pages/upload/upload.js
const app = getApp();

// 引入插件：微信同声传译
const plugin = requirePlugin('WechatSI');

Page({
  data: {
    imageList: "/pages/data/add.jpg",
    info: "",
    count: 0,
    method: "",
    resultAndPrevention: "", // 用于存储结果和防治措施的文本
    src: '', // 路径
    isPlaying: false, // 用于跟踪音频播放状态
  },

  getResultAndPrevention() {
    let that = this;
    wx.request({
      url: 'http://192.168.13.218:5000/getResult',       
      method: "GET",
      data: {
        query: '你是谁'
      },
      success: (res) => {
        console.log(res);
        let result = res.data;
        wx.request({
          url: 'http://192.168.13.218:5000/getMethod',       
          method: "GET",
          success: (res) => {
            console.log(res);
            let prevention = res.data;
            that.setData({
              resultAndPrevention: `${result}\n\n防治措施：${prevention}`
            });
            that.start(); // 开始播报
          }
        });
      }
    });
  },

  // 定义按钮事件处理函数
  btnTapHandler(e) {
    console.log(e);
    this.setData({
      count: this.data.count + e.target.dataset.info
    });
  },

  uploadImage() {
    let that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        that.setData({
          imageList: res.tempFilePaths[0]
        });
      }
    });
  },

  request() {
    let that = this;
    wx.uploadFile({
      url: 'http://192.168.13.218:5000/request',       
      filePath: that.data.imageList,
      name: 'img',
      success: function (res) {
        console.log(res);
        console.log("Upload success");
        wx.downloadFile({
          url: 'http://192.168.13.218:5000/get',       
          success: function (res) {
            console.log("Download success");
            console.log(res);
            if (res.statusCode == 200) {
              console.log(res.tempFilePath);
              that.setData({ imageList: res.tempFilePath });
            }
          },
          fail: function (res) {
            console.log("Download fail");
            console.log(res);
          }
        });
      },
      fail: function (res) {
        console.log(res);
        console.log("Upload fail");
      }
    });
  },

  // 页面加载时初始化 audio 上下文
  onReady: function () {
    this.initInnerAudioContext();
  },

  // 初始化 audio 上下文的方法
  initInnerAudioContext: function () {
    if (!this.innerAudioContext) {
      this.innerAudioContext = wx.createInnerAudioContext();
      this.innerAudioContext.onError((res) => {
        console.log(res);
        wx.showToast({
        title: '语音播放失败',
        icon: 'none',
      });
      });
      this.innerAudioContext.onEnded(() => {
        this.playNextAudio();
      });
    }
  },

  // 文字转语音
  start: function () {
    const content = this.data.resultAndPrevention;
    if (!content) {
      wx.showToast({
        title: '无内容可播报',
        icon: 'none',
      });
      return;
    }
    const maxLength = 100; // 单次TTS的最大字符数
    let parts = this.splitText(content, maxLength);
    this.speakParts(parts);
  },

  // 分割文本
  splitText(text, maxLength) {
    let parts = [];
    let part = '';
    for (let i = 0; i < text.length; i++) {
      let char = text[i];
      let length = encodeURIComponent(char).length;
      if (part.length + length > maxLength) {
        parts.push(part);
        part = char;
      } else {
        part += char;
      }
    }
    if (part.length > 0) {
      parts.push(part);
    }
    return parts;
  },

  // 播报分割后的文本
  speakParts(parts) {
    this.audioParts = parts; // 存储所有音频部分
    this.currentAudioIndex = 0; // 当前音频索引
    this.playNextAudio(); // 播放第一个音频
  },

  // 播放下一个音频
  playNextAudio: function () {
    if (this.currentAudioIndex < this.audioParts.length) {
      let part = this.audioParts[this.currentAudioIndex];
      this.currentAudioIndex++;
      this.playAudio(part);
    } else {
      console.log("所有音频已播放完毕");
    }
  },

  // 播放音频
  playAudio: function (text) {
    if (!text) {
      wx.showToast({
        title: '无内容可播报',
        icon: 'none',
      });
      return;
    }
    // 引入插件：微信同声传译
    const plugin = requirePlugin('WechatSI');
    plugin.textToSpeech({
      lang: "zh_CN",
      tts: true,
      content: text,
      success: (res) => {
        console.log("succ tts", res);
        console.log("语音文件URL:", res.filename);
        this.setData({
          src: res.filename
        });
        this.yuyinPlay();
      },
      fail: (res) => {
        console.log("fail tts", res);
      }
    });
  },

  // 播放语音
  yuyinPlay: function () {
    if (this.data.src === '') {
      console.log("暂无语音");
      return;
    }
    // 确保 innerAudioContext 已初始化
    if (!this.innerAudioContext) {
      console.error("innerAudioContext is undefined, initializing...");
      this.initInnerAudioContext();
    }
    this.innerAudioContext.src = this.data.src; // 设置音频地址
    if (!this.data.isPlaying) {
      this.innerAudioContext.play(); // 播放音频
      this.setData({ isPlaying: true });
    } else {
      this.innerAudioContext.pause(); // 暂停音频
      this.setData({ isPlaying: false });
    }
  },

  // 结束语音
  end: function () {
    if (this.innerAudioContext) {
      this.innerAudioContext.pause(); // 暂停音频
      this.setData({ isPlaying: false });
    }
  },

  // 点击Logo图片，暂停或继续播放
  logoTap: function () {
    if (this.innerAudioContext) {
      if (this.data.isPlaying) {
        this.innerAudioContext.pause(); // 暂停音频
      } else {
        this.innerAudioContext.play(); // 继续播放音频
      }
      this.setData({ isPlaying: !this.data.isPlaying });
    }
  },
});